import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private redisService: RedisService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET,
    });
  }

  async validate(payload: any) {
    // 从 Redis 验证 token
    const storedToken = await this.redisService.get(`token:${payload.userId}`);
      if (!storedToken) {
      console.log('token校验 token已失效')
      throw new UnauthorizedException('Token已失效');
    }
    
    return { userId: payload.userId, userName: payload.userName, avatar: payload.avatar };
  }
}